<?php

/**
 * controller for the user profil
 * 
 * @author Youssef Driouach
 *
 */
class ProfilController extends Zend_Controller_Action
{
	public function init()
	{
		$title ="User";
		$this->view->__set("headtitle", $title);
		/* Initialize path to js and css resources here */
		$baseurl = $this->getFrontController()->getBaseUrl();
		$this->view->headLink()->appendStylesheet($baseurl."/css/jquery.Jcrop.min.css");
		$this->view->headScript()->appendFile( $baseurl."/js/jcrop/jquery.min.js", $type = 'text/javascript' );
		$this->view->headScript()->appendFile( $baseurl."/js/jcrop/jquery.Jcrop.min.js", $type = 'text/javascript' );
		$this->view->headScript()->appendFile( $baseurl."/js/jcrop/script.js", $type = 'text/javascript' );
	}
	
	public function indexAction()
	{
		// the get parameters
		$id_user = $this->_request->getParam("id_user");
		$userMapper = new Application_Model_UserMapper();
		$userOwner = new Application_Model_User();
		$userConnected = new Application_Model_User();
		$is_mine = false;
		$error = null;
		$form = new Application_Form_Avatar('avatar');
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$userConnected = $userMapper->find($auth->getIdentity()->id_user);
			// Change avatar
			$iWidth = $iHeight = 200; // desired image result dimensions
			$iJpgQuality = 90;
			if($this->_request->isPost()){
				$formData = $this->getRequest()->getPost();
				if($form->isValid($formData))
				{
					//TODO revoir le code et l'adapter.
					// new unique filename
                    $sTempFileName = PUBLIC_PATH.'/img/profil/' . md5(time().rand());

                    // move uploaded file into cache folder
                    move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);

                    // change file permission to 644
                    @chmod($sTempFileName, 0644);

                    if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
                        $aSize = getimagesize($sTempFileName); // try to obtain image info
                        if (!$aSize) {
                            @unlink($sTempFileName);
                            return;
                        }

                        // check for image type
                        switch($aSize[2]) {
                            case IMAGETYPE_JPEG:
                                $sExt = '.jpg';

                                // create a new image from file 
                                $vImg = @imagecreatefromjpeg($sTempFileName);
                                break;
                            /*case IMAGETYPE_GIF:
                                $sExt = '.gif';

                                // create a new image from file 
                                $vImg = @imagecreatefromgif($sTempFileName);
                                break;*/
                            case IMAGETYPE_PNG:
                                $sExt = '.png';

                                // create a new image from file 
                                $vImg = @imagecreatefrompng($sTempFileName);
                                break;
                            default:
                                @unlink($sTempFileName);
                                return;
                        }

                        // create a new true color image
                        $vDstImg = @imagecreatetruecolor( $iWidth, $iHeight );

                        // copy and resize part of an image with resampling
                        imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);

                        // define a result image filename
                        $sResultFileName = $sTempFileName . $sExt;

                        // output image to file
                        imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
                        @unlink($sTempFileName);
                        $userMapper->updateAvatar($userConnected->getUserId(), basename($sResultFileName));
                        $this->_helper->redirector($userConnected->getUserId(), 'profil' );
                    }
				}
			}
		}
		if(is_numeric($id_user))
		{
			$userOwner = $userMapper->find($id_user);
		}
		
		if($userConnected == $userOwner)
		{
			$is_mine = true;
		}
		if($userOwner == null)
			$error = "User not founded";
		$this->view->form = $form;
		$this->view->userConnected = $userConnected;
		$this->view->userOwner = $userOwner;
		$this->view->is_mine = $is_mine;
		$this->view->alert = $error;
		
		
	}
	
	public function editAction()
	{
		$userMapper = new Application_Model_UserMapper();
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$form = new Application_Form_User('user');
			$userConnected = $userMapper->find($auth->getIdentity()->id_user);
			$form->populate(array(
									'firstName' => $userConnected->getFirstName(),
									'LastName' 	=> $userConnected->getLastName(),
									'sex' 		=> $userConnected->getSex(),
									'mobile'	=> $userConnected->getMobile(),
									));
			if($this->_request->isPost()){
				$formData = $this->getRequest()->getPost();
				if($form->isValid($formData))
				{
					$userConnected->setFirstName($form->getValue('firstName'))
					->setLastName($form->getValue('LastName'))
					->setSex($form->getValue('sex'))
					->setMobile($form->getValue('mobile'));
					$id_user = $userMapper->edit($userConnected);
					$this->_helper->redirector($id_user, 'profil' );
					//Edit only first and last name sex and mobile
				}
			}
				
			$this->view->form = $form;
		}else{
			
			$this->_helper->redirector ( 'index', 'index' );
		}
		
	}
	
	public function passwordAction()
	{
		$userMapper = new Application_Model_UserMapper();
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$form = new Application_Form_Password('password');
			$userConnected = $userMapper->find($auth->getIdentity()->id_user);
			
			if($this->_request->isPost()){
				$formData = $this->getRequest()->getPost();
				if($form->isValid($formData) && $userConnected->getPassword() == sha1($form->getValue('oldpwd')))
				{
					$userConnected->setPassword(sha1($form->getValue('newpwd')));
					$id_user = $userMapper->editPassword($userConnected);
					$this->_helper->redirector($id_user, 'profil' );
					//Edit only first and last name sex and mobile
				}
			}
	
			$this->view->form = $form;
		}else{
			
			$this->_helper->redirector ( 'index', 'index' );
		}
	
	}
	
}